// common/logger/logger.config.ts
import { utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import * as path from 'path';

// 日志级别定义
export enum LogLevel {
  ERROR = 'error',
  WARN = 'warn',
  INFO = 'info',
  HTTP = 'http',
  VERBOSE = 'verbose',
  DEBUG = 'debug',
  SILLY = 'silly',
}

// 日志配置选项接口
export interface LoggerOptions {
  logLevel: LogLevel;    // 应该使用 logLevel
  logDir: string;
  maxFiles: string;
  maxSize: string;
  disableConsole?: boolean;
}

// 默认日志配置
export const defaultLoggerOptions: LoggerOptions = {
  logLevel: (process.env.LOG_LEVEL as LogLevel) || LogLevel.INFO,
  logDir: path.join(process.cwd(), 'logs'),
  maxFiles: '14d',
  maxSize: '20m',
};

/**
 * 创建Winston日志配置
 * @param options 日志配置选项
 * @returns Winston日志配置
 */
export const createWinstonOptions = (options: LoggerOptions = defaultLoggerOptions) => {
  const { logLevel, logDir, maxFiles, maxSize, disableConsole } = options;
  
  // 控制台日志格式
  const consoleFormat = winston.format.combine(
    winston.format.timestamp(),
    winston.format.ms(),
    nestWinstonModuleUtilities.format.nestLike('CookAPI', {
      colors: true,
      prettyPrint: true,
    }),
  );

  // 文件日志格式
  const fileFormat = winston.format.combine(
    winston.format.timestamp(),
    winston.format.json(),
  );

  // 日志传输配置
  const transports: winston.transport[] = [];

  // 添加控制台传输
  if (!disableConsole) {
    transports.push(
      new winston.transports.Console({
        format: consoleFormat,
        level: process.env.NODE_ENV === 'production' ? LogLevel.WARN : logLevel,
      }),
    );
  }

  // 添加常规日志文件传输
  transports.push(
    new DailyRotateFile({
      dirname: logDir,
      filename: 'application-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      maxSize,
      maxFiles,
      level: logLevel,
      format: fileFormat,
    }),
  );

  // 添加错误日志文件传输
  transports.push(
    new DailyRotateFile({
      dirname: logDir,
      filename: 'error-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      maxSize,
      maxFiles,
      level: LogLevel.ERROR,
      format: fileFormat,
    }),
  );

  return {
    transports,
    // 捕获异常并记录
    exceptionHandlers: [
      new DailyRotateFile({
        dirname: logDir,
        filename: 'exceptions-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        maxSize,
        maxFiles,
        format: fileFormat,
      }),
    ],
  };
};